﻿using System;
using System.Collections.Generic;
using HYCodeBase.Geometry;
using NetTopologySuite.Geometries;

namespace HYCodeBase.TopologySuite
{
	public class HYPolygonFinder
	{
		public bool TryGetPolygons(List<HYMulPointXYZ> lstInputCurves, out List<HYPolygon> lstFindedPolygons, out List<HYPolygon> lstCreatedPolygons, bool ifSplitInput = false)
		{
			lstFindedPolygons = new List<HYPolygon>();
			lstCreatedPolygons = new List<HYPolygon>();
			if (lstInputCurves == null)
			{
				return false;
			}
			this.m_core = new PolygonFinder();
			List<LineString> list = new List<LineString>();
			LineString lineString = null;
			NtsGeometryGeter ntsGeometryGeter = NtsGeometryGeter.GetNtsGeometryGeter();
			foreach (HYMulPointXYZ inputPoints in lstInputCurves)
			{
				if (ntsGeometryGeter.TryMakeLineString(inputPoints, out lineString, false) && null != lineString)
				{
					list.Add(lineString);
				}
			}
			List<Polygon> lstInput = null;
			List<Polygon> lstInput2 = null;
			if (!this.m_core.FindPolygon(list, out lstInput, out lstInput2, ifSplitInput))
			{
				return false;
			}
			this.m_core = null;
			return this.TryTransformOneLstPolygon(lstInput, ref lstFindedPolygons) && this.TryTransformOneLstPolygon(lstInput2, ref lstCreatedPolygons);
		}

		public bool TryGetConvexHullPolygon(List<HYMulPointXYZ> lstInputCurves, out HYPolygon findPolygon)
		{
			findPolygon = null;
			this.m_core = new PolygonFinder();
			List<LineString> list = new List<LineString>();
			LineString lineString = null;
			NtsGeometryGeter ntsGeometryGeter = NtsGeometryGeter.GetNtsGeometryGeter();
			foreach (HYMulPointXYZ inputPoints in lstInputCurves)
			{
				if (!ntsGeometryGeter.TryMakeLineString(inputPoints, out lineString, false))
				{
					return false;
				}
				if (null != lineString)
				{
					list.Add(lineString);
				}
			}
			Polygon item = null;
			if (!this.m_core.FindConvexHull(list, out item))
			{
				return false;
			}
			List<HYPolygon> list2 = new List<HYPolygon>();
			List<Polygon> lstInput = new List<Polygon>
			{
				item
			};
			if (!this.TryTransformOneLstPolygon(lstInput, ref list2) || list2.Count < 1)
			{
				return false;
			}
			findPolygon = list2[0];
			return true;
		}

		private bool TryTransformOneLstPolygon(List<Polygon> lstInput, ref List<HYPolygon> creatLst)
		{
			HYPolygon hypolygon = null;
			if (creatLst == null)
			{
				creatLst = new List<HYPolygon>();
			}
			using (List<Polygon>.Enumerator enumerator = lstInput.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					if (!NTSTransformer.TryChangePolygonToHYPolygon(enumerator.Current, out hypolygon))
					{
						return false;
					}
					if (hypolygon != null)
					{
						creatLst.Add(hypolygon);
					}
				}
			}
			return true;
		}

		private PolygonFinder m_core;
	}
}
